package com.changgou.seckill.timer;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import entity.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 定时将秒杀商品存入redis缓存
 */
@Component
public class SeckillGoodsPushTask {
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 每30秒执行一次,测试改5s
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void loadGoodsPushRedis(){
//        System.out.println("task demo");
        //获取当前时间菜单
        List<Date> dateMenus = DateUtil.getDateMenus();
        //循环查询每个时间段的秒杀商品
        for (Date dateMenu : dateMenus) {
            //作为redis的key
            String timeSpace= "SeckillGoods_"+DateUtil.data2str(dateMenu,"yyMMddHH");
            System.out.println(timeSpace);
            //检测商品状态
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            //审核通过
            criteria.andEqualTo("status","1");
            //库存>0
            criteria.andGreaterThan("stockCount",0);
            //开始时间大于等于当前时间,结束时间必须大于等于当前时间
            criteria.andGreaterThanOrEqualTo("startTime",dateMenu);
            criteria.andLessThan("endTime", DateUtil.addDateHour(dateMenu,2));
            //排除已经存入的数据
            Set keys= redisTemplate.boundHashOps(dateMenu).keys();
            if(keys!=null && keys.size()>0) {
                criteria.andNotIn("id", keys);
            }
            //查询数据
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            //存入redis
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(timeSpace).put(seckillGood.getId(),seckillGood);
                redisTemplate.boundListOps("SeckillGoodsCountList_"+seckillGood.getId()).leftPushAll(
                        pushIds(seckillGood.getStockCount(),seckillGood.getId())
                );
                //自增计数器
                redisTemplate.boundHashOps("SeckillGoodsCount").increment(seckillGood.getId(),seckillGood.getStockCount());
            }
        }


    }
    /***
     * 将商品ID存入到数组中
     * @param len:长度
     * @param id :值
     * @return
     */
    public Long[] pushIds(int len,Long id){
        Long[] ids = new Long[len];
        for (int i = 0; i <ids.length ; i++) {
            ids[i]=id;
        }
        return ids;
    }
}
